const { getPool } = require('../config/db')
const bcrypt = require('bcryptjs')

class User {
  static async createUser(username, password, email, phone, nickname, role, role_id) {
    const mysqlPool = await getPool()
    const hashedPassword = await bcrypt.hash(password, 10)
    const [rows] = await mysqlPool.execute('INSERT INTO users (username, password, email, phone, nickname, role, role_id) VALUES (?,?,?,?,?,?,?)', [username, hashedPassword, email, phone, nickname, role, role_id])
    return rows.insertId
  }
  static async update(username, email, phone, nickname, role, role_id, id) {
    const mysqlPool = await getPool()
    const [rows] = await mysqlPool.execute('UPDATE users SET username=?, email=?, phone=?, nickname=?, role=?, role_id =? WHERE id =?', [username, email, phone, nickname, role, role_id, id])

    return rows.insertId
  }
  static async getUserByUsername(username) {
    const mysqlPool = await getPool()
    const [rows] = await mysqlPool.execute('SELECT * FROM users WHERE username =?', [username])
    return rows[0]
  }

  static async getUserByUserAll() {
    const mysqlPool = await getPool()
    const [rows] = await mysqlPool.execute('SELECT * FROM users', [])
    return rows
  }
  static async login(username, password) {
    const mysqlPool = await getPool()
    const [rows] = await mysqlPool.execute('SELECT * FROM users WHERE username = ?', [username])
    if (rows.length === 0) {
      // console.log('用户不存在')
      return null
    }
    const user = rows[0]
    const isMatch = await bcrypt.compare(password, user.password)
    if (isMatch) {
      // console.log('密码匹配')
      return user
    } else {
      // console.log(' ===== 密码不匹配 ===== ')
      return null
    }
  }
  static async testBcrypt() {
    // console.log(' ===== testBcrypt ===== ')
    const password = '123456'
    const hashedPassword = await bcrypt.hash(password, 10)
    const isMatch = await bcrypt.compare(password, hashedPassword)
    // console.log('Test isMatch:', isMatch)
  }
  static async resetPassword(id) {
    const mysqlPool = await getPool()
    const password = '123456'
    const hashedPassword = await bcrypt.hash(password, 10)
    const [rows] = await mysqlPool.execute('UPDATE users SET password=? WHERE id =?', [hashedPassword, id])
    return rows.insertId
  }
  static async updatePassword(val) {
    const mysqlPool = await getPool()

    // 1. 从数据库中获取用户的当前密码
    const [userRows] = await mysqlPool.execute('SELECT password FROM users WHERE id = ?', [val.id])
    if (userRows.length === 0) {
      return { success: false, code: 404, message: '用户不存在', data: null } // 用户不存在
    }

    const currentPassword = userRows[0].password // 获取当前密码

    // 2. 验证原密码
    const isOldPasswordValid = await bcrypt.compare(val.oldPassword, currentPassword)
    if (!isOldPasswordValid) {
      return { success: false, code: 400, message: '原密码不正确', data: null } // 原密码不正确
    }

    // 3. 加密新密码
    const hashedPassword = await bcrypt.hash(val.password, 10)

    // 4. 提取对象的键值对
    const keys = Object.keys(val)
    const values = Object.values(val)

    // 5. 排除 id 字段，因为它用于 WHERE 条件
    const setClause = keys
      .filter((key) => key !== 'id' && key !== 'oldPassword') // 排除 id 和 oldPassword
      .map((key) => `${key}=?`) // 生成 SET 部分
      .join(', ') // 用逗号连接

    // 6. 生成 SQL 语句
    const sqlStr = `UPDATE users SET ${setClause} WHERE id=?`

    // 7. 生成参数数组（排除 id 和 oldPassword 的值，并将其放在最后）
    const params = [
      ...values
        .filter((_, index) => keys[index] !== 'id' && keys[index] !== 'oldPassword') // 排除 id 和 oldPassword
        .map((value, index) => (keys[index] === 'password' ? hashedPassword : value)), // 替换密码为加密后的值
      val.id, // 添加 id 到参数数组末尾
    ]

    // 8. 执行 SQL
    const [rows] = await mysqlPool.execute(sqlStr, params)

    return { success: true, code: 200, message: '密码更新成功', data: { insertId: rows.insertId } } // 返回更新结果
  }
}

module.exports = User
